<template>
  <div class="message-home-page">
    <!-- 用户选项弹窗 -->
    <div v-if="showUserOptionsModal" class="user-options-modal-overlay" @click="closeUserOptionsModal">
      <div class="user-options-modal" @click.stop>
        <div class="user-option" @click="goToPersonalHome">
          <span class="option-icon">👤</span>
          <span class="option-text">个人主页</span>
        </div>
        <div class="user-option" @click="logout">
          <span class="option-icon">🚪</span>
          <span class="option-text">退出登录</span>
        </div>
      </div>
    </div>
    
    <!-- 主内容区域 -->
    <div class="main-content">
      <!-- 顶部搜索和用户区域 -->
      <div class="top-bar">
        <div class="left-aligned-header-items">
          <div class="header-logo" @click="goToMainHome">
            <img src="../assets/logo.png" alt="Logo" class="logo">
            <span class="logo-text">小白盒</span>
          </div>
          <TopBarSearch />
        </div>
        <div class="user-profile">
          <img :src="currentUser.avatar || 'https://placehold.co/30x30'" alt="用户头像" class="user-avatar" @click="toggleUserOptionsModal">
          <span class="username" @click="toggleUserOptionsModal" style="cursor: pointer;">{{ currentUser.nickname || '未登录' }}</span>
          <span class="message-icon" @click="refreshMessageHome"></span>
        </div>
      </div>

      <!-- 主内容区域 -->
      <div class="main-sections-wrapper">
        <div class="main-sections">
          <!-- 最近消息区域 -->
          <div class="recent-messages-section">
            <div class="section-title">最近消息</div>
            <div class="search-messages">
              <img width="20" height="20" src="https://img.icons8.com/material-outlined/48/search-client.png" alt="search-client"/>
              <input type="text" placeholder="搜索好友" v-model="recentSearchQuery">
            </div>
            <div class="message-list-scrollable">
              <div v-for="(msg, index) in filteredRecentMessages" :key="index" class="message-item" @click="handleMessageClick(msg)">
                <div class="message-avatar">
                  <img :src="msg.avatar || 'https://placehold.co/50x50?text=用户'" alt="用户头像">
                </div>
                <div class="message-details">
                  <div class="message-header">
                    <div class="message-title">{{ msg.nickName || '用户' }}</div>
                    <div class="message-time">{{ formatMessageTime(msg.lastMessageTime) }}</div>
                  </div>
                  <div class="message-footer">
                    <div class="message-content">{{ msg.lastMessage || '暂无消息' }}</div>
                    <div v-if="msg.unreadCount && msg.unreadCount > 0" class="unread-badge">{{ msg.unreadCount }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 主内容区（评论/私信） -->
          <div style="flex:1; min-width:0;">
            <div v-if="activeView === 'comments'" class="all-comments-section">
              <!-- 评论区标签页 -->
              <div class="comment-tabs">
                <div class="tab-item" :class="{ active: activeCommentTab === 'all-comments' }" @click="handleTabClick('all-comments')">所有评论</div>
                <div class="tab-item" :class="{ active: activeCommentTab === 'likes' }" @click="handleTabClick('likes')">赞</div>
                <div class="tab-item" :class="{ active: activeCommentTab === 'followed' }" @click="handleTabClick('followed')">关注</div>
              </div>

              <!-- 评论内容 -->
              <div class="comment-list-scrollable">
                <div v-if="activeCommentTab === 'all-comments'" class="comments-content">
                  <!-- 加载状态 -->
                  <div v-if="isLoading" class="loading-indicator">
                    <p>加载中...</p>
                  </div>
                  
                  <!-- 空数据提示 -->
                  <div v-else-if="comments.length === 0" class="empty-content">
                    <p>暂无评论通知</p>
                  </div>
                  
                  <!-- 评论列表 -->
                  <div v-else v-for="(comment, index) in comments" :key="index" class="comment-item" @click="goToCommentDetail(comment.postId, comment.commentId)">
                    <!-- 评论者头像和信息 -->
                    <div class="comment-user-info">
                      <div class="comment-avatar">
                        <img :src="comment.commenterAvatar" alt="评论者头像">
                      </div>
                      <div class="comment-user-details">
                        <div class="comment-user-name">{{ comment.commenterNickname }}</div>
                        <div class="comment-time">{{ comment.commentTime }}</div>
                        <div class="comment-content">{{ comment.commentContent }}</div>
                      </div>
                    </div>
                    
                    <!-- 被评论的文章/动态内容 -->
                    <div class="commented-content">
                      <div class="activity-content">{{ comment.articleTitle }}</div>
                    </div>
                  </div>
                </div>

                <div v-else-if="activeCommentTab === 'likes'" class="likes-content">
                  <!-- 加载状态 -->
                  <div v-if="isLoading" class="loading-indicator">
                    <p>加载中...</p>
                  </div>
                  
                  <!-- 空数据提示 -->
                  <div v-else-if="likes.length === 0" class="empty-content">
                    <p>暂无点赞通知</p>
                  </div>
                  
                  <!-- 点赞列表 -->
                  <div v-else v-for="(like, index) in likes" :key="index" class="like-item">
                    <!-- 点赞用户信息 -->
                    <div class="like-user-info">
                      <div class="like-avatar" v-if="like.likers && like.likers.length > 0">
                        <img :src="like.likers[0].avatar || 'https://img.icons8.com/material/48/guest-male--v1.png'" alt="点赞用户头像">
                      </div>
                      <div class="like-icon" v-else>
                        <img src="/点赞.png" alt="点赞图标">
                      </div>
                      <div class="like-user-details">
                        <div class="like-first-line">
                          <span class="like-username">{{ like.likers && like.likers.length > 0 ? like.likers[0].nickname : like.displayNicknames }}</span>
                          <span class="like-action">赞了你的动态</span>
                        </div>
                        <div class="like-time">{{ formatLikeTime(like.likeTime) }}</div>
                      </div>
                    </div>
                    
                    <!-- 被点赞的文章/动态内容 -->
                      <div class="liked-content" @click="goToArticleDetail(like.postId)" role="button">
                        <div class="activity-content">{{ like.articleTitle }}</div>
                      </div>
                  </div>
                </div>

                <div v-else-if="activeCommentTab === 'followed'" class="following-content">
                  <!-- 加载状态 -->
                  <div v-if="isLoading" class="loading-indicator">
                    <p>加载中...</p>
                  </div>
                  
                  <!-- 空数据提示 -->
                  <div v-else-if="followers.length === 0" class="empty-content">
                    <p>暂无关注通知</p>
                  </div>
                  
                  <!-- 关注列表 -->
                  <div v-else v-for="(follower, index) in followers" :key="index" class="follower-item">
                    <div class="follower-user-info">
                      <div class="comment-avatar">
                        <img :src="follower.followerAvatar || 'https://img.icons8.com/material/48/guest-male--v1.png'" alt="关注者头像">
                      </div>
                      <div class="follower-user-details">
                        <div class="follower-nickname">{{ follower.followerNickname || '关注者' }}</div>
                        <div class="follow-action">关注了你</div>
                        <div class="follow-time">{{ follower.followTime }}</div>
                      </div>
                    </div>
                  </div>
                </div>

                <div v-else-if="activeCommentTab === 'at-me'" class="at-me-content">
                  <p>这里显示\"@我的\"内容。</p>
                </div>

                <div class="load-more">暂无更多内容</div>
              </div>
            </div>
            <PrivateChat
              v-else-if="activeView === 'privateChat'"
              class="private-chat-section"
              :current-user-id="loginUserId"
              :target-user-id="currentUserId"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import PrivateChat from '../components/PrivateChat.vue';
import TopBarSearch from '../components/TopBarSearch.vue';
import axios from 'axios';
import { currentUser } from '../user';

const router = useRouter();
const route = useRoute();
const showUserOptionsModal = ref(false);
function goToMainHome() {
  router.push('/mainpage').then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
}

function goToPersonalHome() {
  router.push(`/user/${currentUser.id}`);
}

// 切换用户选项弹窗
function toggleUserOptionsModal() {
  showUserOptionsModal.value = !showUserOptionsModal.value;
}

// 关闭用户选项弹窗
function closeUserOptionsModal() {
  showUserOptionsModal.value = false;
}

// 退出登录
function logout() {
  // 清空用户信息
  currentUser.id = null;
  currentUser.nickname = '默认用户';
  currentUser.avatar = '';
  
  // 清除本地存储
  localStorage.removeItem('user');
  
  // 跳转到登录页面
  router.push('/login').then(() => {
    // 页面跳转后刷新页面
    window.location.reload();
  });
  closeUserOptionsModal();
}

const activeCommentTab = ref('all-comments');
const recentSearchQuery = ref(''); // 最近消息搜索
const activeView = ref('comments'); // 'comments' or 'privateChat'
const currentUserId = ref(null); // 当前聊天的 userId
const loginUserId = ref(null); // 登录用户的 userId
const isLoading = ref(false); // 加载状态

const recentMessages = ref([]);
const comments = ref([]); // 评论通知
const likes = ref([]); // 点赞通知
const followers = ref([]); // 关注通知

const filteredRecentMessages = computed(() => {
  if (!recentSearchQuery.value) return recentMessages.value;
  return recentMessages.value.filter(msg =>
    msg.nickName && msg.nickName.toLowerCase().includes(recentSearchQuery.value.toLowerCase())
  );
});

function handleTabClick(tab) {
  activeCommentTab.value = tab;
  if (tab === 'all-comments') {
    fetchComments();
  } else if (tab === 'likes') {
    fetchLikes();
  } else if (tab === 'followed') {
    fetchFollowers();
  }
}

// 获取评论通知
async function fetchComments() {
  // 设置加载状态
  isLoading.value = true;
  comments.value = []; // 清空现有数据
  
  try {
    const userId = loginUserId.value;
    // 使用固定的API路径
    const apiPath = 'http://localhost:8087/api/comment-notifications';
    
    let response = null;
    
    try {
      console.log(`请求路径: ${apiPath}`);
      response = await axios.get(apiPath, { params: { userId } });
      console.log(`成功获取数据，使用路径: ${apiPath}`);
    } catch (e) {
      console.log(`路径 ${apiPath} 请求失败: ${e.message}`);
      isLoading.value = false;
      return;
    }
    
    if (!response || !response.data) {
      console.log('API返回无效数据，显示暂无内容');
      isLoading.value = false;
      return;
    }
    
    // 处理响应数据
    console.log('评论通知数据:', response.data);
    comments.value = response.data.map(notification => {
      return {
        id: notification.id || Math.random().toString(36).substr(2, 9),
        postId: notification.activity_id || '1',
        commentId: notification.id || '1',
        commenterAvatar: notification.comment_user_avatar || 'https://placehold.co/40x40',
        commenterNickname: notification.comment_user_name || '评论者',
        commentContent: notification.comment_content || '评论内容',
        commentTime: new Date(notification.comment_time || Date.now()).toLocaleString(),
        articleTitle: notification.activity_content ? notification.activity_content.substring(0, 30) + '...' : '文章标题',
        articleAuthor: '作者',
        articleCover: 'https://placehold.co/100x60'
      };
    });
    
    // 重置加载状态
    isLoading.value = false;
  } catch (error) {
    console.error('获取评论通知失败:', error);
    comments.value = [];
  }
}

// 格式化点赞时间
function formatLikeTime(timeStr) {
  const likeTime = new Date(timeStr);
  const now = new Date();
  const diffHours = Math.floor((now - likeTime) / (1000 * 60 * 60));
  
  // 判断是否是今天
  const isToday = likeTime.getDate() === now.getDate() && 
                  likeTime.getMonth() === now.getMonth() && 
                  likeTime.getFullYear() === now.getFullYear();
                  
  if (isToday) {
    // 今天内的显示为"几小时前"或"刚刚"
    if (diffHours === 0) {
      const diffMinutes = Math.floor((now - likeTime) / (1000 * 60));
      if (diffMinutes < 1) {
        return '刚刚';
      } else {
        return `${diffMinutes}分钟前`;
      }
    } else {
      return `${diffHours}小时前`;
    }
  } else {
    // 非今天的显示为具体日期
    return `${likeTime.getFullYear()}/${likeTime.getMonth() + 1}/${likeTime.getDate()}`;
  }
}

// 格式化消息时间
function formatMessageTime(timeStr) {
  if (!timeStr) return '';
  
  const msgTime = new Date(timeStr);
  const now = new Date();
  
  // 检查日期是否有效
  if (isNaN(msgTime.getTime())) {
    return timeStr; // 如果日期无效，直接返回原始字符串
  }
  
  // 判断是否是今天
  const isToday = msgTime.getDate() === now.getDate() && 
                  msgTime.getMonth() === now.getMonth() && 
                  msgTime.getFullYear() === now.getFullYear();
  
  // 判断是否是昨天
  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  const isYesterday = msgTime.getDate() === yesterday.getDate() && 
                      msgTime.getMonth() === yesterday.getMonth() && 
                      msgTime.getFullYear() === yesterday.getFullYear();
  
  if (isToday) {
    // 今天内的显示为具体时间 HH:MM
    return msgTime.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
  } else if (isYesterday) {
    // 昨天的显示为"昨天"
    return '昨天';
  } else {
    // 更早的显示为具体日期，不显示年份
    return `${msgTime.getMonth() + 1}月${msgTime.getDate()}日`;
  }
}

// 跳转到文章详情页
function goToArticleDetail(postId) {
  if (!postId) return;
  
  // 使用 router.push 方法进行导航，使用命名路由
  router.push({
    name: 'ActivityDetail',
    params: { id: postId }
  });
  
  console.log(`跳转到文章详情页: ActivityDetail, id=${postId}`);
}

// 跳转到评论详情页
function goToCommentDetail(postId, commentId) {
  if (!postId) return;
  
  // 使用 router.push 方法进行导航，使用命名路由并传递评论ID作为查询参数
  router.push({
    name: 'ActivityDetail',
    params: { id: postId },
    query: { commentId: commentId }
  });
  
  console.log(`跳转到评论详情页: ActivityDetail, id=${postId}, commentId=${commentId}`);
}

// 获取点赞通知
async function fetchLikes() {
  // 设置加载状态
  isLoading.value = true;
  likes.value = []; // 清空现有数据
  
  try {
    const userId = loginUserId.value;
    // 使用固定的API路径
    const apiPath = 'http://localhost:8087/api/like-notifications';
    
    let response = null;
    
    try {
      console.log(`请求路径: ${apiPath}`);
      response = await axios.get(apiPath, { params: { userId } });
      console.log(`成功获取数据，使用路径: ${apiPath}`);
    } catch (e) {
      console.log(`路径 ${apiPath} 请求失败: ${e.message}`);
      isLoading.value = false;
      return;
    }
    
    if (!response || !response.data) {
      console.log('API返回无效数据，显示暂无内容');
      isLoading.value = false;
      return;
    }
    
    // 处理响应数据
    console.log('点赞通知数据:', response.data);
    
    // 按文章ID分组
    const groupedByPost = {};
    const userInfoPromises = [];
    
    response.data.forEach(notification => {
      const postId = notification.activity_id || '1';
      
      if (!groupedByPost[postId]) {
        groupedByPost[postId] = {
          id: notification.id || Math.random().toString(36).substr(2, 9),
          postId: postId,
          likers: [],
          articleTitle: notification.activity_content ? notification.activity_content.substring(0, 30) + '...' : '文章标题',
          articleAuthor: '作者',
          articleCover: notification.activity_cover || 'https://placehold.co/100x60',
          likeTime: notification.create_time || new Date().toISOString(),
          recentLikes: [] // 存储6小时内的点赞
        };
      }
      
      // 添加点赞者信息
      const likerName = notification.sender_name || '用户';
      const likerId = notification.sender_id;
      
      // 如果有发送者ID，获取用户详细信息
      if (likerId) {
        const userPromise = axios.get(`http://localhost:8084/api/user/${likerId}`)
          .then(res => {
            const userData = res.data;
            return {
              id: likerId,
              nickname: userData.nickname || likerName,
              avatar: userData.avatar || 'https://img.icons8.com/material/48/guest-male--v1.png',
              time: notification.create_time
            };
          })
          .catch(err => {
            console.error(`获取用户信息失败 ID:${likerId}`, err);
            return {
              id: likerId,
              nickname: likerName,
              avatar: 'https://img.icons8.com/material/48/guest-male--v1.png',
              time: notification.create_time
            };
          });
        
        userInfoPromises.push({ postId, userPromise });
      } else {
        // 如果没有发送者ID，使用通知中的基本信息
        groupedByPost[postId].likers.push({
          id: likerId,
          nickname: likerName,
          avatar: notification.sender_avatar || 'https://img.icons8.com/material/48/guest-male--v1.png',
          time: notification.create_time
        });
      }
      
      // 如果是同一天内的点赞，添加到最近点赞列表
      const today = new Date();
      const likeDate = new Date(notification.create_time);
      if (likeDate.getDate() === today.getDate() && 
          likeDate.getMonth() === today.getMonth() && 
          likeDate.getFullYear() === today.getFullYear()) {
        groupedByPost[postId].recentLikes.push(likerName);
      }
    });
    
    // 等待所有用户信息请求完成
    Promise.all(userInfoPromises.map(item => item.userPromise))
      .then(results => {
        // 将获取到的用户信息添加到对应的帖子中
        results.forEach((userInfo, index) => {
          const { postId } = userInfoPromises[index];
          if (groupedByPost[postId]) {
            groupedByPost[postId].likers.push(userInfo);
          }
        });
        
        // 转换为数组并处理显示逻辑
        likes.value = Object.values(groupedByPost).map(post => {
          // 对点赞者按时间排序，最新的在前面
          post.likers.sort((a, b) => new Date(b.time) - new Date(a.time));
          
          // 处理显示的昵称列表
          let displayNames = '';
          if (post.recentLikes.length > 0) {
            // 最多显示4个名字
            const nameList = post.recentLikes.slice(0, 4);
            const totalLikers = post.recentLikes.length;
            if (totalLikers > 4) {
              displayNames = nameList.join('、') + `等${totalLikers}人`;
            } else {
              displayNames = nameList.join('、');
            }
          } else {
            displayNames = post.likers[0]?.nickname || '用户';
          }
          
          return {
            id: post.id,
            postId: post.postId,
            displayNicknames: displayNames,
            articleTitle: post.articleTitle,
            articleAuthor: post.articleAuthor,
            articleCover: post.articleCover,
            likeTime: post.likeTime
          };
        });
      })
      .catch(error => {
        console.error('获取用户信息失败:', error);
        likes.value = [];
      });
    
    // 重置加载状态
    isLoading.value = false;
    
    // 重置加载状态
    isLoading.value = false;
  } catch (error) {
    console.error('获取点赞通知失败:', error);
    likes.value = [];
  }
}

// 获取关注通知
async function fetchFollowers() {
  // 设置加载状态
  isLoading.value = true;
  followers.value = []; // 清空现有数据
  
  try {
    const userId = loginUserId.value;
    // 使用固定的API路径
    const apiPath = 'http://localhost:8087/api/follow-notifications';
    
    let response = null;
    
    try {
      console.log(`请求路径: ${apiPath}`);
      response = await axios.get(apiPath, { params: { userId } });
      console.log(`成功获取数据，使用路径: ${apiPath}`);
    } catch (e) {
      console.log(`路径 ${apiPath} 请求失败: ${e.message}`);
      isLoading.value = false;
      return;
    }
    
    if (!response || !response.data) {
      console.log('API返回无效数据，显示暂无内容');
      isLoading.value = false;
      return;
    }
    
    // 处理响应数据
    console.log('关注通知数据:', response.data);
    
    // 创建用户信息获取的Promise数组
    const userInfoPromises = [];
    
    // 先处理基本数据
    const followersData = response.data.map(notification => {
      const followerId = notification.follower_id;
      
      // 如果有关注者ID，创建获取用户信息的Promise
      if (followerId) {
        const userPromise = axios.get(`http://localhost:8084/api/user/${followerId}`)
          .then(res => {
            return {
              id: notification.id || Math.random().toString(36).substr(2, 9),
              followerId: followerId,
              followerAvatar: res.data.avatar || notification.follower_avatar || 'https://img.icons8.com/material/48/guest-male--v1.png',
              followerNickname: res.data.nickname || notification.follower_name || '关注者',
              followTime: new Date(notification.follow_time || Date.now()).toLocaleString()
            };
          })
          .catch(err => {
            console.error(`获取用户信息失败 ID:${followerId}`, err);
            return {
              id: notification.id || Math.random().toString(36).substr(2, 9),
              followerId: followerId,
              followerAvatar: notification.follower_avatar || 'https://img.icons8.com/material/48/guest-male--v1.png',
              followerNickname: notification.follower_name || '关注者',
              followTime: new Date(notification.follow_time || Date.now()).toLocaleString()
            };
          });
        
        userInfoPromises.push(userPromise);
      } else {
        // 如果没有关注者ID，使用通知中的基本信息
        return {
          id: notification.id || Math.random().toString(36).substr(2, 9),
          followerId: followerId,
          followerAvatar: notification.follower_avatar || 'https://img.icons8.com/material/48/guest-male--v1.png',
          followerNickname: notification.follower_name || '关注者',
          followTime: new Date(notification.follow_time || Date.now()).toLocaleString()
        };
      }
    }).filter(item => item); // 过滤掉undefined项
    
    // 等待所有用户信息请求完成
    const userResults = await Promise.all(userInfoPromises);
    
    // 合并结果
    followers.value = [...followersData, ...userResults];
    
    // 重置加载状态
    isLoading.value = false;
  } catch (error) {
    console.error('获取关注通知失败:', error);
    followers.value = [];
  }
}

function handleRecentSearchBlur(event) {
  // 如果点击的不是最近消息搜索框，清空 recentSearchQuery
  const input = document.querySelector('.recent-messages-section input');
  if (input && event.target !== input) {
    recentSearchQuery.value = '';
  }
}

onMounted(() => {
  document.body.addEventListener('click', handleRecentSearchBlur, true);
  // 从localStorage获取当前用户信息
  const userStr = localStorage.getItem('user');
  if (userStr) {
    try {
      const user = JSON.parse(userStr);
      if (user && user.id) {
        loginUserId.value = user.id;
        // 默认将当前聊天用户ID也设置为登录用户ID
        currentUserId.value = user.id;
      }
    } catch (error) {
      console.error('解析用户信息失败:', error);
    }
  } else if (currentUser.id) {
    // 如果localStorage中没有，则使用currentUser
    loginUserId.value = currentUser.id;
  }
  
  // 初始加载所有通知类型
  fetchComments(); // 初始加载评论通知
});
onBeforeUnmount(() => {
  document.body.removeEventListener('click', handleRecentSearchBlur, true);
});

// 获取最近消息列表
async function fetchRecentMessages() {
  try {
    console.log('当前用户ID:', loginUserId.value, '类型:', typeof loginUserId.value);
    // 使用登录用户ID获取最近消息
    const userId = loginUserId.value;
    const url = `http://localhost:8082/api/messages/sessions/${userId}`;
    console.log('请求URL:', url);
    const res = await axios.get(url);
    
    if (res.data && res.data.code === 200 && Array.isArray(res.data.data)) {
      console.log('最近消息数据:', res.data.data);
      recentMessages.value = res.data.data;
    } else {
      console.log('接口返回数据格式不正确');
      recentMessages.value = [];
    }
  } catch (error) {
    console.error('获取最近消息失败:', error.response?.status, error.response?.data);
    console.error('错误详情:', error);
    recentMessages.value = [];
  }
}

// 建立WebSocket连接
function setupWebSocket() {
  const userId = loginUserId.value;
  if (!userId) return;
  
  const wsUrl = `ws://localhost:8082/websocket/chat/${userId}`;
  const socket = new WebSocket(wsUrl);
  
  socket.onopen = () => {
    console.log('WebSocket连接已建立');
    // 连接成功后立即获取一次最新数据
    fetchRecentMessages();
  };
  
  socket.onmessage = (event) => {
    console.log('收到WebSocket消息:', event.data);
    try {
      const data = JSON.parse(event.data);
      if (Array.isArray(data)) {
        // 直接更新消息列表
        recentMessages.value = data;
      } else if (data.type === 'NEW_MESSAGE') {
        // 收到新消息，刷新消息列表
        fetchRecentMessages();
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error);
    }
  };
  
  socket.onclose = () => {
    console.log('WebSocket连接已关闭');
    // 尝试重新连接
    setTimeout(setupWebSocket, 3000);
  };
  
  socket.onerror = (error) => {
    console.error('WebSocket错误:', error);
    // 连接失败时尝试使用HTTP请求获取数据
    fetchRecentMessages();
  };
  
  // 保存WebSocket实例以便后续使用
  return socket;
}

let wsConnection = null;

onMounted(async () => {
  // 初始加载消息列表
  await fetchRecentMessages();
  
  // 建立WebSocket连接
  wsConnection = setupWebSocket();
});

onBeforeUnmount(() => {
  // 组件卸载前关闭WebSocket连接
  if (wsConnection && wsConnection.readyState === WebSocket.OPEN) {
    wsConnection.close();
  }
});



const handleMessageClick = (msg) => {
  console.log('点击的消息对象:', msg);
  if (msg.friendId) {
    // 使用 friendId 字段
    currentUserId.value = msg.friendId;
    activeView.value = 'privateChat'; // 切换到私信界面
  } else {
    console.error('User ID is undefined');
  }
};

// 消息图标点击事件，返回到消息主界面
function refreshMessageHome() {
  // 切换回评论界面，不显示私聊
  activeView.value = 'comments';
  // 如果URL中有私聊参数，清除它们
  if (route.query.view === 'privatechat') {
    router.replace({ path: '/messagehome' });
  }
}

// 在组件挂载时检查 URL 参数
onMounted(() => {
  // 获取登录用户ID
  loginUserId.value = currentUser.id;
  
  // 检查 URL 参数中是否有目标用户信息
  if (route.query.targetUserId && route.query.view === 'privatechat') {
    // 设置当前聊天的用户ID
    currentUserId.value = parseInt(route.query.targetUserId);
    // 切换到私聊界面
    activeView.value = 'privateChat';
  }
  
  // 加载消息列表
  fetchRecentMessages();
  fetchComments();
});


</script>

<style scoped>

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: hidden;
}

.top-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  height: 50px;
}

.left-aligned-header-items {
  display: flex;
  align-items: center;
  flex-grow: 1;
  width: 100%;
}

.inline-sidebar .publish-btn {
  width: auto;
  padding: 10px 20px;
  font-size: 14px;
}

.header-logo {
  display: flex;
  align-items: center;
  height: 100%;
  margin-left: 24px;
  cursor: pointer;
}

.logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.logo-text {
  font-size: 20px;
  font-weight: bold;
  margin-right: 60px;
  width: 100px;
  color: #333;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  justify-content: center; /* 水平居中 */
  flex-grow: 1;
  width: 100%;
  max-width: 450px;
  border: 1px solid #ddd;
  border-radius: 20px;
  padding: 5px 15px;
  background-color: #f5f5f5;
  margin: 0 auto; /* 自动外边距实现整体居中 */
}

.search-input-wrapper input {
  border: none;
  outline: none;
  flex-grow: 1;
  padding: 5px;
  background-color: transparent;
  font-size: 14px;
  text-align: center; /* 输入框内文字居中 */
}

.header-logo {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 100px;
}

.user-profile {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 100px;
}

.user-avatar {
  border-radius: 50%;
  margin-right: 10px;
  width: 30px;
  height: 30px;
}

.username {
  font-weight: bold;
  margin-right: 20px;
  font-size: 15px;
  color: #000;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 120px;
}

/* 用户选项弹窗样式 */
.user-options-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
  z-index: 1000;
}

.user-options-modal {
  position: absolute;
  top: 50px;
  right: 100px;
  width: 150px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.user-option {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-option:hover {
  background-color: #f5f5f5;
}

.option-icon {
  margin-right: 10px;
  font-size: 18px;
}

.option-text {
  font-size: 14px;
  color: #000000;
}

.message-icon {
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: inline-block;
  background-image: url('https://img.icons8.com/sf-regular/48/messaging-.png');
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  text-indent: -9999px; /* 隐藏文字 */
}

.main-sections-wrapper {
  flex-grow: 1;
  margin-top: 50px; /* Account for top-bar height */
  padding: 20px;
  overflow-y: auto;
  height: calc(100vh - 50px);
  width: 100%; /* 添加宽度100% */
}

.main-sections {
  display: flex;
  flex-grow: 1;
  gap: 20px;
  height: 100%;
  width: 100%; /* 添加宽度100% */
  padding: 0 100px; /* 添加左右内边距以创建空白 */
}

.recent-messages-section {
  flex-basis: 300px;
  flex-shrink: 0;
  background-color: #fff;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
  display: flex;
  flex-direction: column;
  height: 100%; /* 使用百分比高度 */
  margin-top: 0;
  border-right: 1px solid #eee;
  width: 300px; /* 添加固定宽度 */
}

.section-title {
  padding: 12px 20px; /* 调整内边距 */
  font-size: 16px; /* 调整字体大小 */
  font-weight: bold;
  color: #000000;
  border-bottom: 1px solid #eee;
  height: 45px; /* 固定高度 */
  display: flex;
  align-items: center;
}

.search-messages {
  padding: 8px 20px; /* 调整内边距 */
  border-bottom: 1px solid #eee;
  background-color: #fff;
  display: flex;
  align-items: center;
  height: 40px; /* 固定高度 */
}

.search-messages input {
  border: none;
  outline: none;
  flex-grow: 1;
  padding: 0 5px;
  font-size: 13px;
}

.message-list-scrollable {
  flex-grow: 1;
  overflow-y: auto;
  padding: 0;
  width: 100%; /* 添加宽度100% */
}

.message-item {
  padding: 12px 20px; /* 调整内边距 */
  border-bottom: 1px solid #eee;
  background-color: #fff;
  border-radius: 0;
  box-shadow: none;
  min-height: 60px; /* 设置最小高度 */
  width: 100%; /* 添加宽度100% */
  display: flex; /* 使用flex布局 */
  align-items: center; /* 垂直居中 */
}

.message-item:hover {
  background-color: #f0f0f0; /* 悬停时的背景颜色 */
}

.message-avatar {
  width: 40px; /* 调整尺寸 */
  height: 40px; /* 调整尺寸 */
  border-radius: 50%;
  margin-right: 10px;
  flex-shrink: 0;
}

.message-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.message-details {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 4px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-title {
  font-weight: bold;
  color: #333;
  font-size: 14px; /* 调整字体大小 */
  margin-right: 8px;
}

.message-time {
  color: #999; /* 调整颜色 */
  font-size: 12px;
  white-space: nowrap;
}

.message-content {
  color: #555; /* 调整颜色 */
  line-height: 1.5; /* 调整行高 */
  font-size: 13px; /* 调整字体大小 */
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 70%;
}

.all-comments-section {
  flex-grow: 1;
  background-color: #fff;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
  display: flex;
  flex-direction: column;
  height: 100%; /* 使用百分比高度 */
  width: 100%; /* 添加宽度100% */
}

.comment-tabs {
  padding: 0;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: flex-start;
  gap: 20px;
  flex-shrink: 0;
  height: 45px; /* 固定高度 */
}

.tab-item {
  padding: 0 20px; /* 调整内边距 */
  cursor: pointer;
  font-weight: bold;
  color: #555;
  position: relative;
  font-size: 14px;
  border-bottom: 2px solid transparent;
  height: 100%; /* 占满容器高度 */
  display: flex;
  align-items: center;
}

.tab-item.active {
  color: #333;
  border-bottom: 2px solid #333;
}

.comment-list-scrollable {
  flex-grow: 1;
  overflow-y: auto;
  padding: 0;
  width: 100%; /* 添加宽度100% */
}

.comment-item {
  padding: 12px 20px; /* 调整内边距 */
  border-bottom: 1px solid #eee;
  background-color: #fff;
  border-radius: 0;
  box-shadow: none;
  min-height: 60px; /* 设置最小高度 */
  width: 100%; /* 添加宽度100% */
}

.comment-item:hover {
  background-color: #f0f0f0; /* 悬停时的背景颜色 */
}

.comment-avatar {
  width: 40px; /* 调整尺寸 */
  height: 40px; /* 调整尺寸 */
  border-radius: 50%;
  margin-right: 10px;
  flex-shrink: 0;
}

.comment-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.comment-time {
  color: #999; /* 调整颜色 */
  font-size: 12px;
  margin-left: 0px;
}

.comment-content {
  color: #555; /* 调整颜色 */
  margin-top: 5px;
  line-height: 1.5; /* 调整行高 */
  font-size: 13px; /* 调整字体大小 */
}

/* 点赞通知样式 */
.like-item {
  padding: 8px;
  border-bottom: 1px solid #eee;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.like-user-info {
  display: flex;
  align-items: flex-start;
}

.like-icon {
  width: 40px;
  height: 40px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.like-icon img {
  width: 30px;
  height: 30px;
}

.like-avatar {
  width: 40px;
  height: 40px;
  margin-right: 8px;
  border-radius: 50%;
  overflow: hidden;
}

.like-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.like-user-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.like-first-line {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-bottom: 2px;
}

.like-username {
  font-size: 14px;
  color: #333;
  font-weight: 600;
}

.like-time {
  font-size: 12px;
  color: #999;
}

.like-action {
  font-size: 14px;
  color: #666;
}

.liked-content {
  margin-left: 48px;
  margin-top: -2px;
  padding: 8px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.liked-content:hover {
  background-color: #e8edf5;
}

.content-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.activity-content {
  flex: 1;
}

.reply-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.nested-reply-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.load-more {
  text-align: center;
  padding: 15px;
  color: #999; /* 调整颜色 */
  font-size: 14px; /* 调整字体大小 */
  flex-shrink: 0; /* 防止加载更多文本收缩 */
}

.likes-content, .following-content, .at-me-content {
  padding: 20px;
  text-align: center;
  color: #666;
  flex-grow: 1; /* 确保这些内容区域也能扩展 */
  overflow-y: auto; /* 确保这些内容区域也能滚动 */
  width: 100%; /* 添加宽度100% */
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@media (max-width: 768px) {

}

@media (max-width: 480px) {

}

/* 新增样式 */
.at-me-content p {
  padding: 20px;
  text-align: center;
  color: #999;
}

.comment-item, .follower-item {
  display: flex;
  flex-direction: column;
  padding: 15px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
}

.like-item {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 评论通知样式 */
.comment-user-info, .follower-user-info {
  display: flex;
  margin-bottom: 10px;
}

.like-user-info {
  display: flex;
  margin-bottom: 10px;
  align-items: flex-start;
}

.comment-avatar img, .follower-avatar img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 15px;
  object-fit: cover;
}

.follower-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

/* 点赞图标样式 */
.like-icon {
  width: 35px;
  height: 35px;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.like-icon img {
  width: 35px;
  height: 35px;
  object-fit: contain;
}

.comment-user-details, .follower-user-details {
  flex: 1;
}

.like-user-details {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
}

.comment-user-name, .follower-nickname {
  color: #000000;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 2px;
}

.like-username {
  font-size: 14px;
  margin-bottom: 5px;
  display: flex;
  align-items: center;
}

.like-username span {
  font-weight: bold;
  margin-left: 5px;
}

.comment-time, .follow-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.like-time {
  font-size: 12px;
  color: #999;
  position: absolute;
  right: 20px;
  top: 15px;
}

.comment-content, .follow-action {
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.like-action {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.commented-content {
  background-color: #f5f5f5;
  padding: 10px;
  border-radius: 5px;
  margin-top: 5px;
  font-size: 13px;
  color: #666;
}

.liked-content {
  background-color: #f5f5f5;
  padding: 10px;
  margin-left: 34px;
  border-radius: 4px;
  margin-top: 0;
}

.activity-content {
  word-break: break-all;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

</style>
